<!--
 * @FilePath: /web-vue/src/views/HouseImage/index.vue
 * @Description: 【房源图片】管理主页
-->
<template>
  <div>
    <el-row :gutter="0">
      <!-- 【房源图片】参数 -->
      <el-col>
        <el-form :model="queryForm" size="medium" :inline="true">
          <table
            style="border-collapse: collapse; width: 100%"
            class="table-common-style"
          >
            <colgroup>
              <col width="11.11%" />
              <col width="11.11%" />
              <col width="11.11%" />
              <col width="11.11%" />
              <col width="11.11%" />
              <col width="11.11%" />
              <col width="11.11%" />
              <col width="11.11%" />
              <col width="11.11%" />
            </colgroup>
            <tbody>
              <tr>
                <td colspan="10">
                  <!-- 按钮 -->
                  <el-form-item>
                    <el-button
                      type="primary"
                      icon="el-icon-search"
                      @click="queryDataBtn()"
                      :loading="requestLoading"
                      >查询
                    </el-button>
                    <el-button
                      type="success"
                      icon="el-icon-document-add"
                      @click="$refs.addForm.openAddForm(true)"
                      >新增
                    </el-button>
                    <el-button
                      type="danger"
                      icon="el-icon-delete"
                      @click="batchDelHouseImageApi()"
                      >批量删除
                    </el-button>
                  </el-form-item>
                </td>
              </tr>
            </tbody>
          </table>
        </el-form>
      </el-col>
      <!-- 【房源图片】信息表 -->
      <el-col>
        <el-table
          :data="tableData"
          row-key="id"
          max-height="400"
          border
          highlight-current-row
          v-loading="requestLoading"
          element-loading-text="正在拼命加载，请耐心等待！"
          element-loading-spinner="el-icon-loading"
          @selection-change="handleTableRowsSelect"
          @current-change="handleTableCurrentRowChange"
        >
          <el-table-column type="selection" width="55" align="center">
          </el-table-column>
          <el-table-column
            fixed="left"
            label="操作"
            width="100%"
            align="center"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-edit-outline"
                @click="$refs.editForm.openEditForm(true, scope.row)"
                >变更
              </el-button>
            </template>
          </el-table-column>
          <el-table-column
            type="index"
            label="序号"
            width="80"
            align="center"
          ></el-table-column>
          <el-table-column prop="imageUrl" label="房源图片" align="center">
            <template slot-scope="scope">
              <el-image
                style="width: 100px; height: 100px"
                :src="`${$store.state.API_ROOT}${scope.row.imageUrl}`"
                :preview-src-list="[
                  `${$store.state.API_ROOT}${scope.row.imageUrl}`,
                ]"
              >
              </el-image>
            </template>
          </el-table-column>
          <el-table-column prop="imageStatus" label="图片状态" align="center">
            <template slot-scope="scope">
              <template
                v-for="(item, index) in $store.state.DICT.imageStatusSelect"
              >
                <el-tag
                  v-if="item.code === scope.row.imageStatus"
                  :key="index"
                  :type="item.theme"
                >
                  {{ item.name }}
                </el-tag>
              </template>
            </template>
          </el-table-column>
          <el-table-column
            prop="sort"
            label="排序值"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="houseId"
            label="房源ID"
            align="center"
          ></el-table-column>
        </el-table>
      </el-col>
      <!-- 分页组件 -->
      <el-col>
        <el-pagination
          background
          @size-change="handlePageSizeChange"
          @current-change="handleCurrentPageChange"
          :current-page="page.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="page.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total"
          align="center"
        >
        </el-pagination>
      </el-col>
    </el-row>

    <!-- 添加房源图片表单 -->
    <AddForm
      :item="houseItem"
      ref="addForm"
      @afterSubmit="afterSubmitHandle()"
    ></AddForm>
    <!-- 编辑房源图片表单 -->
    <EditForm ref="editForm" @afterSubmit="afterSubmitHandle()"></EditForm>
  </div>
</template>

<script>
import AddForm from "./addForm";
import EditForm from "./editForm";
import {
  DateTimeRange_Picker_Option,
  DateRange_Picker_Option,
  Date_Picker_Option,
} from "@/utils/datePicker";

export default {
  name: "houseImageManage",
  props: ["houseItem"],
  components: {
    AddForm,
    EditForm,
  },

  data() {
    return {
      // 分页参数
      page: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
      },
      // 【房源图片】数据表
      tableData: [],
      // 【房源图片】表已选 IDs
      tableCheckIds: [],
      // 数据加载
      requestLoading: false,
      // 查询表单参数
      queryForm: {
        id: null,
        houseId: null,
        imageUrl: null,
        sort: null,
        imageStatus: null,
      },
      // 日期选择快捷方式
      DateTimeRange_Picker_Option,
      DateRange_Picker_Option,
      Date_Picker_Option,
    };
  },

  // 组件创建时
  created() {
    // 页面元素初始化
  },

  // 组件挂载时
  mounted() {
    this.queryDataBtn();
  },

  watch: {
    houseItem() {
      this.queryDataBtn();
    },
  },

  methods: {
    // 表单提交后置处理
    afterSubmitHandle() {
      this.queryHouseImageApi();
      this.tableCheckIds = [];
    },

    // 处理表格行多选
    handleTableRowsSelect(val) {
      let ids = [];
      val.forEach((obj) => ids.push(obj.id));
      this.tableCheckIds = ids;
    },

    // 处理表格行单选
    handleTableCurrentRowChange(row, oldRow) {},

    // ---------------- 分页参数处理 START-----------------
    handleCurrentPageChange(val) {
      this.page.currentPage = val;
      // 查询【房源图片】表
      this.queryHouseImageApi();
    },
    handlePageSizeChange(val) {
      this.page.pageSize = val;
      this.page.currentPage = 1;
      // 查询【房源图片】表
      this.queryHouseImageApi();
    },
    // ---------------- 分页参数处理 END-----------------

    // 查询【房源图片】
    queryDataBtn() {
      this.page.currentPage = 1;
      this.queryHouseImageApi();
    },

    // 删除数据后：最后一页逻辑处理、表格更新
    afterDelete(deleteCount) {
      // 最后一页（旧）
      let oldLastPage = Math.ceil(this.page.total / this.page.pageSize);
      // 最后一页（新）
      let currLastPage = Math.ceil(
        (this.page.total - deleteCount) / this.page.pageSize
      );
      // 如果删除最后一页，则将当前页更新为最新的最后一页
      if (this.page.currentPage == oldLastPage) {
        this.page.currentPage = currLastPage == 0 ? 1 : currLastPage;
      }
      // 更新表格
      this.queryHouseImageApi();
    },

    // 查询参数处理
    queryParamProcess() {
      let param = Object.assign({}, this.queryForm);
      param["pageNum"] = this.page.currentPage;
      param["pageSize"] = this.page.pageSize;

      param["houseId"] = this.houseItem.id;

      return param;
    },

    // 查询【房源图片】API
    queryHouseImageApi() {
      this.requestLoading = true;

      this.$api
        .queryHouseImage(this.queryParamProcess())
        .then((res) => {
          this.tableData = [];
          this.page.total = 0;

          let { status, message, data } = res.data;
          if (status == 200) {
            this.tableData = data.items;
            this.page.total = data.totalNum;
          } else if (status == 403) {
            this.$message({
              message: `权限不足！${message}`,
              type: "error",
              center: true,
              duration: 1680,
            });
          } else {
            this.$alert(`暂无数据记录！${message}`, "【房源图片】信息表", {
              type: "info",
              confirmButtonText: "确定",
              callback: (action) => {},
            });
          }

          this.requestLoading = false;
        })
        .catch((err) => {
          this.requestLoading = false;
          console.log(`【房源图片】查询接口发生错误: ${err}`);
        });
    },

    // 删除【房源图片】API
    batchDelHouseImageApi() {
      if (this.tableCheckIds.length == 0) {
        this.$alert("请在左侧列选中要删除的数据行！", "提示", {
          confirmButtonText: "确定",
          type: "warning",
          callback: (action) => {},
        });
        return;
      }

      this.$confirm("此操作将永久删除已选中的数据, 是否继续?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "error",
      })
        .then(() => {
          const loading = this.$loading({
            target: document.querySelector(".data-table"),
            lock: true,
            text: "正在删除，请耐心等待！",
          });

          // 发起删除请求
          this.$api
            .batchDelHouseImage({ ids: this.tableCheckIds })
            .then((res) => {
              loading.close();

              let { status, message, data } = res.data; // 响应数据
              if (status == 200) {
                // 更新【房源图片】表
                this.afterDelete(data);
                // 提示信息
                this.$message({
                  type: "success",
                  message: `删除成功！删除记录数：${data}`,
                  duration: 1680,
                });
              } else if (status == 403) {
                this.$message({
                  message: `权限不足！${message}`,
                  type: "error",
                  center: true,
                  duration: 1680,
                });
                // this.$router.push("/login");
              } else {
                this.$message({
                  type: "warning",
                  message: `数据没有发生更改！${message}`,
                  duration: 1680,
                });
              }
            })
            .catch((err) => {
              loading.close();
              // 查询【房源图片】表
              this.queryHouseImageApi();
              console.log(`【房源图片】删除接口发生错误: ${err}`);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除。",
          });
        });
    },
  },
};
</script>

<style lang="scss" scoped>
// 表单布局样式
@import "@/assets/css/form-layout.scss";
</style>
